package com.leo.mybatis;

import com.leo.mybatis.mapper.IOrderMapper;
import com.leo.mybatis.mapper.IUserMapper;
import com.leo.mybatis.pojo.Order;
import com.leo.mybatis.pojo.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.io.Reader;
import java.util.List;

public class MybatisTest {

    private IUserMapper userMapper;
    private IOrderMapper orderMapper;
    private SqlSession sqlSession;

    @Before
    public void before() throws IOException {

        //使用InputStream或者Reader都可以
        //InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
        Reader reader = Resources.getResourceAsReader("sqlMapConfig.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        //开启事务自动提交
        sqlSession = sqlSessionFactory.openSession(true);
        userMapper = sqlSession.getMapper(IUserMapper.class);
        orderMapper = sqlSession.getMapper(IOrderMapper.class);
    }

    @After
    public void after(){
        sqlSession.close();
    }


    @Test
    public void addUser(){
        User user = new User();
        user.setId(3);
        user.setUsername("test");

        userMapper.addUser(user);
    }

    @Test
    public void updateUser(){
        User user = new User();
        user.setId(3);
        user.setUsername("test-modify");

        userMapper.updateUser(user);

    }

    @Test
    public void selectUser(){
        List<User> users = userMapper.selectUser();
        for (User user : users) {
            System.out.println(user);
        }
    }

    @Test
    public void deleteUser(){
        userMapper.deleteUser(3);
    }




    @Test
    public void oneToOne(){
        List<Order> orderAndUser = orderMapper.findOrderAndUser();
        for (Order order : orderAndUser) {
            System.out.println(order);
        }

    }

    @Test
    public void oneToMany(){
        List<User> all = userMapper.findAll();
        for (User user : all) {
            System.out.println(user);
        }

    }

    @Test
    public void ManyToMany(){
        List<User> all = userMapper.findAllUserAndRole();
        for (User user : all) {
            System.out.println(user);
        }

    }
}
